package com.muc.plugin.handler;

import com.muc.plugin.dao.MUCDao;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

/**
 * 用戶加群时需要调用此IQ以便存储群昵称, 因为openfire默认机制是群昵称不得重复
 *
 * <iq id='zNstH-8' type='set'>
 *   <query xmlns='xls:muc-join-group-saveOrUpdate'>
 *     <userId>234bb56173d0c4415757d3f7b8178dee@gbei.com</userId>
 *     <roomId>xxxx-tttt-eeee-qqqq-1111</roomId>
 *     <nickName>張三</nickName>
 *   </query>
 * </iq>
 */
public class MUCJoinGroupHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "join group";

    private static final String NAME_SPACE = "xls:muc-join-group-saveOrUpdate";

    private static final Logger log = LoggerFactory.getLogger(MUCJoinGroupHandler.class);

    public MUCJoinGroupHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        Element iq = packet.getElement();
        Element query = iq.element("query");
        Element userId = query.element("userId");
        Element roomId = query.element("roomId");
        Element nickName = query.element("nickName");
        if (null == userId || null == roomId || null == nickName) {
            reply.setError(PacketError.Condition.item_not_found);
        }
        MUCDao.storageUserNickName(userId.getText(), roomId.getText(), nickName.getText());
        reply.setType(IQ.Type.result);
        log.info("success result: " + reply.toXML());
        return reply;
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }
}
